<template>
  <div class="login-container">
    <div class="left-column">
      <img src="../../assets/loginBackground.png" class="image-with-animation" />
    </div>
    <div class="right-column">
      <transition name="fade">
        <el-form
          ref="loginForm"
          :model="loginData"
          :rules="loginRules"
          class="login-form"
        >
          <h1 class="login-title">登录</h1>

          <el-form-item prop="username">
            <el-input
              size="large"
              v-model="loginData.username"
              placeholder="用户名"
            ></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              size="large"
              type="password"
              v-model="loginData.password"
              placeholder="密码"
              show-password
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="large" @click="handleLogin"
              >登录</el-button
            >
            <el-button size="large" @click="router.push('/register')"
              >还没账号,去注册</el-button
            >
          </el-form-item>
        </el-form>
      </transition>
    </div>
  </div>
</template>
<script>
import { reactive, toRefs } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { loginApi, userInfoApi } from '@/api/login'

export default {
  setup() {
    const store = useStore()
    const router = useRouter()
    const data = reactive({
      loginData: {
        username: '',
        password: ''
      }
    })
    const loginRules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
                 {min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                ],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' },
                 {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
                ]
    }
    const handleLogin = () => {
      loginApi(data.loginData).then((res) => {
        if (res) {
          store.commit('setUserInfo', res.data)
          localStorage.setItem('loginData', JSON.stringify(res.data))
          router.push({
            path: '/'
          })
        }
      })
    }
    return { ...toRefs(data), handleLogin, loginRules, router }
  },
  methods: {}
}
</script>
<style scoped>
.login-container {
  display: flex;

  flex-direction: row; /* 更改flex方向为行，使图片和表单在同一行 */
}

.left-column {
  height: 100vh;

  flex: 3; /* 图片占据3/4的空间 */

  display: flex;

  justify-content: flex-start;
}

.right-column {
  flex: 2;

  display: flex;

  flex-direction: column; /* 表单内部元素垂直排列 */

  justify-content: center;

  align-items: center;
}

.image-with-animation {
  width: 100%;
  height: 100%;
  animation: fadeIn 2s ease-in;
  object-fit: cover;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</style>
